package com.mankiw.insight.spring.web;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;

import java.io.File;
import java.io.IOException;

public class EmbeddedTomcatDemo {
    //    public static void main(String[] args) throws LifecycleException {
    public static void a(String[] args) throws LifecycleException {
        int port = 8080;
        Tomcat tomcat = new Tomcat();//创建tomcat对象
        tomcat.setPort(port);//绑定端口
        tomcat.getConnector();

        String contextPath = "";
        String docBase = new File(".").getAbsolutePath();
        Context context = tomcat.addContext(contextPath, docBase);//创建context上下文，这个上下文是和文件夹有关的

        //向tomcat中添加一个servlet对象
        //HttpServlet对象
        tomcat.addServlet(contextPath,"helloServlet",new HttpServlet(){
            @Override
            protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                resp.setContentType("text/html");
                resp.getWriter().write("<h1>Hello World</h1>" + req.getRequestURL().toString() + "<br>");
            }
        });
        //helloservlet到底处理什么样的请求
        context.addServletMappingDecoded("/*","helloServlet");
        tomcat.start();
        System.out.println("tomcat started port:" + port);
    }
}
